import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_play_android/common/common.dart';
import 'package:flutter_play_android/data/api/apis_service.dart';
import 'package:flutter_play_android/data/model/article_model.dart';
import 'package:flutter_play_android/data/model/banner_model.dart';
import 'package:flutter_play_android/ui/base/base_widget.dart';
import 'package:flutter_play_android/ui/publish_articles.dart';
import 'package:flutter_play_android/utils/route_util.dart';
import 'package:flutter_play_android/utils/toast_util.dart';
import 'package:flutter_play_android/widgets/custom_cached_image.dart';
import 'package:flutter_play_android/ui/home/item_article_list.dart';
import 'package:flutter_play_android/widgets/refresh_helper.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class HomeScreen extends BaseWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  BaseWidgetState<BaseWidget> attachState() => _HomeScreenState();
}

class _HomeScreenState extends BaseWidgetState {
  final List<BannerBean> _bannerList = [];

  final List<ArticleBean> _articles = [];

  bool _isShowFAB = false;

  /// 页码，从0开始
  int _page = 0;

  final ScrollController _scrollController = ScrollController();
  final RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    _refreshController.dispose();
    super.dispose();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _bannerList.clear();
    showLoading().then((value) {
      getBannerList();
      getTopArticleList();
    });
    _scrollController.addListener(() {
      if (_scrollController.offset < 200 && _isShowFAB) {
        setState(() {
          _isShowFAB = false;
        });
      } else if (_scrollController.offset >= 200 && !_isShowFAB) {
        setState(() {
          _isShowFAB = true;
        });
      }
    });
  }

  @override
  AppBar attachAppBar() {
    return AppBar(
      title: const Text("Play Android"),
      actions: [
        IconButton(
            icon: const Icon(Icons.add),
            onPressed: () {
              RouteUtil.push(context, const PublishArticleScreen());
            })
      ],
    );
  }

  @override
  Widget attachContentWidget(BuildContext context) {
    return SmartRefresher(
      controller: _refreshController,
      enablePullDown: true,
      enablePullUp: true,
      header: RefreshHeader(),
      footer: RefreshFooter(),
      onRefresh: getTopArticleList,
      onLoading: getMoreArticleList,
      child: ListView.builder(
        itemBuilder: itemView,
        physics: const AlwaysScrollableScrollPhysics(),
        controller: _scrollController,
        itemCount: _articles.length + 1,
      ),
    );
  }

  @override
  Widget? fabWidget() {
    return _isShowFAB
        ? FloatingActionButton(
            heroTag: "home",
            child: const Icon(Icons.arrow_upward),
            onPressed: () {
              /// 回到顶部时要执行的动画
              if (_scrollController.hasClients) {
                _scrollController.animateTo(0,
                    duration: const Duration(milliseconds: 200),
                    curve: Curves.easeIn);
              }
            },
          )
        : null;
  }

  @override
  void onClickErrorWidget() {
    showLoading().then((value) {
      getBannerList();
      getTopArticleList();
    });
  }

  Widget itemView(BuildContext context, int index) {
    if (index == 0) {
      return Container(
        height: 200,
        color: Colors.transparent,
        child: _buildBannerWidget(),
      );
    }
    ArticleBean item = _articles[index - 1];
    return ItemArticleList(item: item);
  }

  /// 构建轮播视图
  Widget _buildBannerWidget() {
    return Offstage(
      offstage: _bannerList.isEmpty,
      child: Swiper(
        itemBuilder: (BuildContext context, int index) {
          if (index >= _bannerList.length ||
              _bannerList[index].imagePath == null) {
            return Container(height: 0);
          } else {
            return InkWell(
              child: CustomCachedImage(
                  imageUrl: _bannerList[index].imagePath ?? ""),
              onTap: () {
                RouteUtil.toWebView(context, _bannerList[index].title ?? "",
                    _bannerList[index].url ?? "");
              },
            );
          }
        },
        itemCount: _bannerList.length,
        autoplay: true,
        pagination: const SwiperPagination(),
        // control: new SwiperControl(),
      ),
    );
  }

  void getBannerList() {
    apiService.getBannerList((BannerModel banner) {
      if (banner.data != null && banner.data!.isNotEmpty) {
        setState(() {
          _bannerList.addAll(banner.data!);
        });
      }
    });
  }

  void getTopArticleList() {
    _page = 0;
    apiService.getArticleList((ArticleModel model) {
      if (model.errorCode == Constants.STATUS_SUCCESS) {
        if (model.data?.datas != null && model.data!.datas!.isNotEmpty) {
          showContent().then((value) {
            _refreshController.refreshCompleted(resetFooterState: true);
            setState(() {
              _articles.addAll(model.data!.datas!);
            });
          });
        } else {
          showEmpty();
        }
      } else {
        showError();
        ToastUtil.show(msg: model.errorMsg);
      }
    }, (DioError error) {
      showError();
    }, _page);
  }

  void getMoreArticleList() {
    _page++;
    apiService.getArticleList((ArticleModel model) {
      if (model.errorCode == Constants.STATUS_SUCCESS) {
        if (model.data?.datas != null && model.data!.datas!.isNotEmpty) {
          _refreshController.loadComplete();
          setState(() {
            _articles.addAll(model.data!.datas!);
          });
        } else {
          _refreshController.loadNoData();
        }
      } else {
        _refreshController.loadFailed();
        ToastUtil.show(msg: model.errorMsg);
      }
    }, (DioError error) {
      _refreshController.loadFailed();
    }, _page);
  }
}
